package com.pinyougou.shop.controller;

import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
public class UploadController {


    //注入FastDFS文件服务器访问的地址fileServerUrl=http://192.168.12.131
    @Value("${fileServerUrl}")
    private String fileServerUrl;
    //文件上传类

    @PostMapping("/upload")
    public Map<String,Object> upload(@RequestParam("file") MultipartFile multipartFile ){
       Map<String,Object> data = new HashMap<>();
       data.put("status",500);


        try {
            //加载追踪服务器的连接地址的配置文件，同时获取到配置文件的全路径
            String conf_filename = this.getClass().getResource("/fastdfs-client.conf").getPath();
            //初始化客户端的全局对象
            ClientGlobal.init(conf_filename);
            //创建存储客户端对象
            StorageClient storageClient =new StorageClient();
            //获取源文件名列如：logo.png
            String originalFilename = multipartFile.getOriginalFilename();
            /**将文件上传到FastDFS文件服务器中
             * FilenameUtils.getExtension(String path)：获取文件的扩展名；png
             * String[] strings = storageClient.upload_file("D:\\test\\123.jpg", "jpg", null);
             */
            String[] arr = storageClient.upload_file(multipartFile.getBytes(), FilenameUtils.getExtension(originalFilename),null);
            /** 拼接返回的 url 和 ip 地址，拼装成完整的 url
             * 参数一：group1(组名)
             * 参数二:M00/00/00/wKjlhVrUqe6AfSHDAAHq2__LLfA498.jpg(远程名称)
             * */
            StringBuilder url = new StringBuilder(fileServerUrl);
            for (String str : arr) {
                url.append("/"+str);
            }
            //url：192.168.229.133/group1/M00/00/00/wKjlhVrUqe6AfSHDAAHq2__LLfA498.jpg
            data.put("status",200);
            data.put("url",url.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return data;
    }
}
